<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="referrer" content="never">
    <meta name="format-detection" content="telephone=no">
    <title>文章抠字工具 | 微信专用版</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入简化版docx解析库（微信环境兼容） -->
    <script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/docx-preview@0.1.14/dist/docx-preview.min.js"></script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-area-height {
                min-height: 150px;
            }
            .rule-item {
                @apply p-3 border rounded-md mb-2 hover:bg-gray-50 transition-all duration-300;
            }
            .rule-item.active {
                @apply border-blue-300 bg-blue-50;
            }
            .btn-effect {
                @apply transform hover:scale-105 transition-all duration-200;
            }
            .mobile-full {
                @apply w-full;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen p-4">
    <div class="max-w-4xl mx-auto bg-white rounded-xl shadow-md p-5">
        <!-- 标题 -->
        <h1 class="text-xl md:text-2xl font-bold text-center text-gray-800 mb-2">文章抠字工具</h1>
        <p class="text-center text-gray-600 mb-6 text-sm">生成记忆训练题，增强记忆力</p>

        <!-- 输入区域 -->
        <div class="mb-6">
            <h2 class="text-lg font-semibold mb-3 text-gray-700 flex items-center">
                <i class="fa fa-file-text-o mr-2 text-blue-500"></i>1. 输入文章
            </h2>
            <!-- 文本输入框（手机上增大高度） -->
            <textarea 
                id="articleInput" 
                class="w-full p-3 border border-gray-300 rounded-lg text-area-height focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all text-sm md:text-base"
                placeholder="在此粘贴文章内容（推荐）..."
            ></textarea>
            
            <!-- 文件上传（微信环境弱化，优先推荐粘贴） -->
            <div class="mt-3 flex flex-wrap items-center gap-2">
                <label class="inline-flex items-center bg-blue-500 text-white px-3 py-2 rounded-md text-sm cursor-pointer hover:bg-blue-600 transition btn-effect">
                    <i class="fa fa-upload mr-1"></i>上传文件
                </label>
                <input type="file" id="fileUpload" accept=".txt,.docx" class="hidden" />
                <span id="fileInfo" class="text-gray-500 text-xs md:text-sm"></span>
                <button 
                    id="clearInput" 
                    class="text-gray-600 hover:text-red-500 transition flex items-center btn-effect text-sm"
                >
                    <i class="fa fa-trash-o mr-1"></i> 清空
                </button>
            </div>
            <p class="text-gray-400 text-xs mt-1">提示：微信中推荐直接粘贴文本，文件上传可能受限</p>
        </div>

        <!-- 规则设置区域 -->
        <div class="mb-6 p-3 bg-gray-50 rounded-lg">
            <h2 class="text-lg font-semibold mb-3 text-gray-700 flex items-center">
                <i class="fa fa-sliders mr-2 text-blue-500"></i>2. 设置抠字规则
            </h2>
            
            <!-- 替换字符设置 -->
            <div class="mb-4 p-2 bg-white border border-gray-200 rounded-lg">
                <label class="block font-medium text-gray-700 mb-1 text-sm">替换字符</label>
                <input type="text" id="replaceChar" value="_" maxlength="1" 
                    class="w-10 p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500">
                <span class="text-gray-500 text-xs ml-2">如：_、*、-等</span>
            </div>
            
            <!-- 规则选择（手机上改为单列紧凑布局） -->
            <div class="space-y-3">
                <!-- 间隔抠字 -->
                <div class="rule-item active" onclick="selectRule('interval')">
                    <label class="flex items-center cursor-pointer text-sm">
                        <input type="radio" name="maskRule" value="interval" checked class="mr-2">
                        <span class="font-medium">间隔抠字</span>
                    </label>
                    <div class="mt-2 ml-5 grid grid-cols-2 gap-2 text-sm">
                        <div>
                            <span>每隔</span>
                            <input type="number" id="intervalNum" value="3" min="1" max="10" 
                                class="w-12 mx-1 p-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500">
                            <span>字</span>
                        </div>
                        <div>
                            <span>抠</span>
                            <input type="number" id="maskLength" value="1" min="1" max="5" 
                                class="w-12 mx-1 p-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500">
                            <span>字</span>
                        </div>
                    </div>
                </div>
                
                <!-- 随机抠字 -->
                <div class="rule-item" onclick="selectRule('random')">
                    <label class="flex items-center cursor-pointer text-sm">
                        <input type="radio" name="maskRule" value="random" class="mr-2">
                        <span class="font-medium">随机抠字</span>
                    </label>
                    <div class="mt-2 ml-5">
                        <input type="range" id="randomPercent" min="10" max="70" value="30" 
                            class="w-36 accent-blue-500">
                        <span id="randomPercentText" class="ml-1 text-sm">30%</span>
                    </div>
                </div>
                
                <!-- 关键词抠字 -->
                <div class="rule-item" onclick="selectRule('keyword')">
                    <label class="flex items-center cursor-pointer text-sm">
                        <input type="radio" name="maskRule" value="keyword" class="mr-2">
                        <span class="font-medium">关键词抠字</span>
                    </label>
                    <div class="mt-2 ml-5">
                        <span class="text-sm">抠除词（逗号分隔）：</span>
                        <input type="text" id="keywords" placeholder="的,是,在" 
                            class="w-full mt-1 p-1.5 border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
            </div>
        </div>

        <!-- 结果展示区域 -->
        <div class="mb-6">
            <h2 class="text-lg font-semibold mb-3 text-gray-700 flex items-center">
                <i class="fa fa-magic mr-2 text-blue-500"></i>3. 抠字结果
            </h2>
            
            <div class="border border-gray-300 rounded-lg overflow-hidden">
                <!-- 结果标签页（手机上更紧凑） -->
                <div class="flex border-b border-gray-200">
                    <div class="flex-1 py-2 px-3 text-center font-medium bg-gray-50 border-r border-gray-200 text-sm">模板1：正常抠字</div>
                    <div class="flex-1 py-2 px-3 text-center font-medium bg-gray-50 text-sm">模板2：反向抠字</div>
                </div>
                
                <!-- 结果文本区域（手机上默认上下排列） -->
                <div class="flex flex-col md:flex-row divide-y md:divide-y-0 md:divide-x divide-gray-200">
                    <!-- 模板1：正常抠字 -->
                    <div id="resultText1" class="p-3 min-h-[120px] bg-white text-sm overflow-auto">
                        请点击"生成"按钮...
                    </div>
                    
                    <!-- 模板2：反向抠字 -->
                    <div id="resultText2" class="p-3 min-h-[120px] bg-white text-sm overflow-auto">
                        请点击"生成"按钮...
                    </div>
                </div>
                
                <!-- 操作按钮（手机上按钮文字简化，增大触控区域） -->
                <div class="p-2 bg-gray-50 flex flex-wrap gap-2 justify-center">
                    <button id="generateResult" class="bg-green-500 text-white px-3 py-2 rounded hover:bg-green-600 transition btn-effect text-sm">
                        <i class="fa fa-cog mr-1"></i> 生成
                    </button>
                    <button id="showAnswer" class="bg-blue-500 text-white px-3 py-2 rounded hover:bg-blue-600 transition btn-effect text-sm">
                        <i class="fa fa-eye mr-1"></i> 原文
                    </button>
                    <button id="copyResult1" class="bg-gray-600 text-white px-3 py-2 rounded hover:bg-gray-700 transition btn-effect text-sm">
                        <i class="fa fa-copy mr-1"></i> 复1
                    </button>
                    <button id="copyResult2" class="bg-gray-600 text-white px-3 py-2 rounded hover:bg-gray-700 transition btn-effect text-sm">
                        <i class="fa fa-copy mr-1"></i> 复2
                    </button>
                </div>
            </div>
        </div>

        <!-- 说明区域（手机上简化文字） -->
        <div class="text-xs text-gray-500 bg-gray-50 p-2 rounded-lg">
            <p><i class="fa fa-info-circle text-blue-500 mr-1"></i>使用说明：</p>
            <ul class="list-disc list-inside ml-1 mt-1 space-y-0.5">
                <li>生成后尝试回忆隐藏的字，再点"原文"对照</li>
                <li>模板1：正常隐藏；模板2：反向隐藏</li>
            </ul>
        </div>
    </div>

    <script>
        // 全局变量
        let originalText = '';
        let currentResults = { template1: '', template2: '' };

        // 选择规则时高亮
        function selectRule(ruleValue) {
            document.querySelectorAll('.rule-item').forEach(el => el.classList.remove('active'));
            document.querySelector(`.rule-item:has(input[value="${ruleValue}"])`)?.classList.add('active');
            document.querySelector(`input[name="maskRule"][value="${ruleValue}"]`).checked = true;
        }

        // 监听文件上传（微信环境特殊处理）
        document.getElementById('fileUpload').addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (!file) return;
            document.getElementById('fileInfo').textContent = `已选：${file.name}`;
            
            try {
                if (file.name.endsWith('.txt')) {
                    // TXT文件处理（微信中相对稳定）
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        originalText = event.target.result;
                        document.getElementById('articleInput').value = originalText.substring(0, 5000); // 限制长度避免卡顿
                    };
                    reader.readAsText(file, 'utf-8');
                } else if (file.name.endsWith('.docx')) {
                    // DOCX文件（微信中兼容性较差，简化处理）
                    alert('微信中docx解析可能不全，建议复制文本粘贴');
                    const arrayBuffer = await file.arrayBuffer();
                    // 简化解析：只提取前500字（避免微信浏览器崩溃）
                    const text = await extractSimpleDocxText(arrayBuffer);
                    originalText = text;
                    document.getElementById('articleInput').value = text || '解析失败，请手动粘贴内容';
                }
            } catch (error) {
                alert('文件解析失败，请尝试粘贴文本');
                console.error('文件解析错误:', error);
            }
        });

        // 简化版docx文本提取（适配微信浏览器）
        async function extractSimpleDocxText(arrayBuffer) {
            try {
                const zip = new JSZip();
                await zip.loadAsync(arrayBuffer);
                const content = await zip.file('word/document.xml')?.async('text') || '';
                // 简单正则提取文本（忽略格式）
                const text = content.replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                return text.substring(0, 5000); // 限制长度
            } catch (e) {
                console.error('docx简化解析失败:', e);
                return '';
            }
        }

        // 清空输入
        document.getElementById('clearInput').addEventListener('click', () => {
            document.getElementById('articleInput').value = '';
            document.getElementById('fileUpload').value = '';
            document.getElementById('fileInfo').textContent = '';
            originalText = '';
            document.getElementById('resultText1').textContent = '请点击"生成"按钮...';
            document.getElementById('resultText2').textContent = '请点击"生成"按钮...';
            currentResults = { template1: '', template2: '' };
        });

        // 随机抠字比例显示
        const randomRange = document.getElementById('randomPercent');
        const randomText = document.getElementById('randomPercentText');
        randomRange.addEventListener('input', () => {
            randomText.textContent = `${randomRange.value}%`;
        });

        // 生成抠字结果（优化微信浏览器性能）
        document.getElementById('generateResult').addEventListener('click', () => {
            const inputText = document.getElementById('articleInput').value.trim();
            if (!inputText) {
                alert('请先输入内容！');
                return;
            }
            originalText = inputText;
            
            // 限制文本长度（微信浏览器性能有限）
            const limitedText = inputText.substring(0, 3000);
            const replaceChar = document.getElementById('replaceChar').value || '_';
            
            // 生成结果
            const rule = document.querySelector('input[name="maskRule"]:checked').value;
            let maskInfo = {};
            
            try {
                if (rule === 'interval') {
                    const interval = parseInt(document.getElementById('intervalNum').value) || 3;
                    const maskLength = parseInt(document.getElementById('maskLength').value) || 1;
                    const validInterval = Math.max(interval, maskLength);
                    maskInfo = maskByInterval(limitedText, validInterval, maskLength, replaceChar);
                } else if (rule === 'random') {
                    const percent = parseInt(document.getElementById('randomPercent').value) / 100 || 0.3;
                    maskInfo = maskByRandom(limitedText, percent, replaceChar);
                } else if (rule === 'keyword') {
                    const keywords = document.getElementById('keywords').value.split(',').map(k => k.trim()).filter(k => k);
                    maskInfo = maskByKeyword(limitedText, keywords, replaceChar);
                }

                document.getElementById('resultText1').textContent = maskInfo.template1;
                document.getElementById('resultText2').textContent = maskInfo.template2;
                currentResults = maskInfo;
            } catch (error) {
                alert('生成失败，请重试');
                console.error('生成错误:', error);
            }
        });

        // 显示原文
        document.getElementById('showAnswer').addEventListener('click', () => {
            if (originalText) {
                document.getElementById('resultText1').textContent = originalText;
                document.getElementById('resultText2').textContent = originalText;
            }
        });

        // 复制功能（微信环境兼容）
        function copyResult(template, buttonId) {
            const text = currentResults[template] || document.getElementById(`resultText${template.replace('template', '')}`).textContent;
            if (!text) return;

            // 微信浏览器复制兼容
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(successCopy(buttonId), failCopy);
            } else {
                // 降级方案：创建临时输入框
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    document.execCommand('copy');
                    successCopy(buttonId);
                } catch (e) {
                    failCopy();
                } finally {
                    document.body.removeChild(textarea);
                }
            }
        }

        // 复制成功反馈
        function successCopy(buttonId) {
            const btn = document.getElementById(buttonId);
            const original = btn.innerHTML;
            btn.innerHTML = '<i class="fa fa-check mr-1"></i> 已复制';
            setTimeout(() => btn.innerHTML = original, 1500);
        }

        // 复制失败反馈
        function failCopy() {
            alert('复制失败，请手动复制');
        }

        // 绑定复制按钮
        document.getElementById('copyResult1').addEventListener('click', () => copyResult('template1', 'copyResult1'));
        document.getElementById('copyResult2').addEventListener('click', () => copyResult('template2', 'copyResult2'));

        // 核心抠字逻辑（与之前一致，略作性能优化）
        function maskByInterval(text, interval, maskLength, replaceChar) {
            const template1 = [];
            const template2 = [];
            let position = 0;
            
            while (position < text.length) {
                const keepLength = Math.min(interval - maskLength, text.length - position);
                // 保留部分
                for (let i = 0; i < keepLength; i++) {
                    const char = text[position + i];
                    template1.push(char);
                    template2.push(replaceChar);
                }
                position += keepLength;
                
                // 抠除部分
                const currentMaskLength = Math.min(maskLength, text.length - position);
                for (let i = 0; i < currentMaskLength; i++) {
                    const char = text[position + i];
                    template1.push(replaceChar);
                    template2.push(char);
                }
                position += currentMaskLength;
            }
            
            return { template1: template1.join(''), template2: template2.join('') };
        }

        function maskByRandom(text, percent, replaceChar) {
            const template1 = [];
            const template2 = [];
            
            for (let i = 0; i < text.length; i++) {
                const char = text[i];
                if (char.trim() === '' || '，。,.;:!?！？'.includes(char)) {
                    template1.push(char);
                    template2.push(char);
                } else {
                    const shouldMask = Math.random() < percent;
                    template1.push(shouldMask ? replaceChar : char);
                    template2.push(shouldMask ? char : replaceChar);
                }
            }
            
            return { template1: template1.join(''), template2: template2.join('') };
        }

        function maskByKeyword(text, keywords, replaceChar) {
            if (keywords.length === 0) {
                return {
                    template1: text,
                    template2: text.split('').map(c => replaceChar).join('')
                };
            }
            
            const maskPositions = new Set();
            keywords.forEach(keyword => {
                let index = 0;
                while ((index = text.indexOf(keyword, index)) !== -1) {
                    for (let i = index; i < index + keyword.length; i++) {
                        maskPositions.add(i);
                    }
                    index += keyword.length;
                }
            });
            
            const template1 = [];
            const template2 = [];
            for (let i = 0; i < text.length; i++) {
                const char = text[i];
                if (maskPositions.has(i)) {
                    template1.push(replaceChar);
                    template2.push(char);
                } else {
                    template1.push(char);
                    template2.push(replaceChar);
                }
            }
            
            return { template1: template1.join(''), template2: template2.join('') };
        }

        // 简化版docx文本提取（仅提取纯文本，忽略格式）
        async function extractSimpleDocxText(arrayBuffer) {
            try {
                const zip = new JSZip();
                await zip.loadAsync(arrayBuffer);
                const docContent = await zip.file('word/document.xml')?.async('text') || '';
                // 简单正则去除XML标签，提取文本
                return docContent.replace(/<[^>]+>/g, '').replace(/&amp;/g, '&')
                    .replace(/&lt;/g, '<').replace(/&gt;/g, '>').substring(0, 1000);
            } catch (e) {
                console.error('docx提取失败:', e);
                return '';
            }
        }

        // 初始化
        window.onload = () => {
            // 微信环境提示
            if (navigator.userAgent.includes('MicroMessenger')) {
                console.log('检测到微信浏览器，启用兼容模式');
            }
        };
    </script>
</body>
</html>
